package com.kaibes.imserver.control.threads;

import java.io.BufferedReader;
import java.io.IOException;

import com.kaibes.imserver.control.UserSocketControl;
import com.kaibes.imserver.model.ActionReaderCallback;

public abstract class ClientStringReader implements Runnable {

	//继续运行,但不执行之后的代码
	public static final int continueInt = 1;
	//停止运行，但不关闭socket
	public static final int breakInt = 2;
	//停止运行，并最终关闭socket
	public static final int stopInt = 3;
	
	protected UserSocketControl userSocketControl;
	private BufferedReader bfReader;
	private int goInt;
	
	public ClientStringReader(UserSocketControl userSocketControl, BufferedReader bfReader) {
		this.userSocketControl = userSocketControl;
		this.bfReader = bfReader;
		this.goInt = continueInt;
	}
	
	@Override
	public void run() {
		boolean flag = true;
		while (flag) {
			try {
				String json = bfReader.readLine();
				
				if (json != null) {
					goInt = parsingData(json);
				} else {
					flag = ActionReaderCallback.closeThreadSocket(userSocketControl);
				}

				if (goInt == continueInt) {
					continue;
				}

				if (goInt == breakInt) {
					flag = ActionReaderCallback.closeThread(userSocketControl);
					break;
				}

				if (goInt == stopInt) {
					flag = ActionReaderCallback.closeThreadSocket(userSocketControl);
					break;
				}
				
			} catch (IOException e) {
				flag = ActionReaderCallback.closeThreadSocket(userSocketControl);
//				e.printStackTrace();
			}
		}
	}
	
	protected abstract int parsingData(String json);

}
